<template>
  <el-row type="flex" align="middle">
    <el-col :span="6" class="u-msg-div">
      <div v-for="(item,index) in msgList" :key="index">
        <div @click="GetDialogue(item.fid)" class="msg-list">
          <el-card shadow="never">
            <el-avatar :size="48" :src="item.face | toFaceUrl">
              <el-avatar icon="el-icon-user-solid" :size="48"></el-avatar>
            </el-avatar>
            <span class="u-msg-name">{{item.name}}</span>
            <el-button icon="el-icon-close" size="mini" class="close-btn" circle @click="open(index,item.fid)"></el-button>
            <el-badge is-dot v-if="item.status == 0"></el-badge>
            <span class="u-msg-date">{{item.date | toTime}}</span>
          </el-card>
        </div>
      </div>
    </el-col>
    <el-divider direction="vertical"></el-divider>
    <!--聊天部分-->
    <el-col :span="18" class="u-msg-div">
      <div class="title-name">
        <span style="color:#fff;font-size:18px">{{friendInfo.name}}</span>
      </div>
      <div class="send-msg-div">
        <div v-if="userMsgList" style="margin-top: 10px;">
          <div v-for="(content,i) in userMsgList" :key="i">
            <!--自己发送的-->
            <div v-if="content.from == userInfo.Uid" class="msg-right">
              <el-avatar :size="48" :src="userInfo.Face | toFaceUrl" class="face-right">
                <el-avatar icon="el-icon-user-solid" :size="48"></el-avatar>
              </el-avatar>
              <span class="content-right">{{content.content}}</span>
            </div>
            <!--收到的-->
            <div v-else class="msg-left">
              <el-avatar style="float:left" :size="48" :src="friendInfo.face | toFaceUrl">
                <el-avatar icon="el-icon-user-solid" :size="48"></el-avatar>
              </el-avatar>
              <div class="content-l-div">
                <span class="content-left">{{content.content}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-input
        class="input-msg"
        type="textarea"
        v-model="msgFrom.content"
        rows="4"
        placeholder="在这里写点什么吧！"
      ></el-input>
      <el-button class="btn-msg" size="small" @click="send">发送</el-button>
    </el-col>
  </el-row>
</template>

<script>
import { getUserMsgList, GetUserMessageById, sendMsg ,readMsg,deleteMsg} from "@/api/message";
import Cookies from 'js-cookie'
import { toFaceUrl } from "@/utils/url";
export default {
  data() {
    return {
      msgList: [],
      userMsgList: [],
      uid: 0,
      friendInfo: {
        face: "",
        name: "",
      },
      formId: {
        id: "",
      },
      msgFrom: {
        fid: "",
        content: "",
      },
    };
  },
  methods: {
    _getUserMsgList() {
      getUserMsgList().then((res) => {
        if (res.data.code === 200) {
          this.msgList = res.data.data.data;
          if (this.msgList && !this.msgFrom.fid) {
            this.GetDialogue(this.msgList[0].fid);
          }
        } else {
          this.$message.error("获取失败");
        }
      });
    },
    GetDialogue(fid) {
      this.formId.id = fid;
      GetUserMessageById(this.formId.id).then((res) => {
        if (res.data.code === 200) {
          this.userMsgList = res.data.data.data;
          this.friendInfo.face = res.data.data.face;
          this.friendInfo.name = res.data.data.name;
          this.msgFrom.fid = fid;
          //已读
          readMsg(fid);
        } else {
          this.$message.error("获取失败");
        }
      });
    },
    open(index,fid){
      this.$confirm('删除后该聊天将不会出现在你的消息记录中, 是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
        this.msgList.splice(index, 1);
        deleteMsg(fid);
        this.$message.success('删除成功');
        
      }).catch(() => {
        this.$message.info('取消删除');
      })
    },
    send() {
      if (this.msgFrom.fid == "") {
        return this.$message.error("请先打开对话");
      }
      if (!this.msgFrom.content.trim()) {
        this.msgFrom.content = "";
        return this.$message.error("请输入内容");
      }
      var content = this.msgFrom.content;
      sendMsg(this.msgFrom).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("发送成功");
          //添加到数组
          this.userMsgList.push({ from: this.uid, content: content });
        } else {
          this.$message.error("发送失败");
        }
      }).catch((err) => {
        this.$message.error(err.response.data.msg);
      });
      this.msgFrom.content = "";
    },
  },
  computed: {
    userInfo() {
      return JSON.parse(Cookies.get('userInfo'));
    },
  },
  created() {
    this._getUserMsgList();
    this.uid = this.userInfo.Uid;
    if (this.$route.params.fid) {
      let newFid = Number(this.$route.params.fid);
      this.msgFrom.fid = newFid;
      this.GetDialogue(this.msgFrom.fid);
    }
  },
  filters: {
    toFaceUrl(name) {
      return toFaceUrl(name);
    },
    toTime(time) {
      var date = new Date(time);
      var year = date.getFullYear();
      var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
      var new_datetime = year + "-" + month + "-" + day + "  " + hours + ":" + minutes + ":" + seconds;
      // 处理成为时间戳
      var timestamp = new Date(Date.parse(new_datetime));
      timestamp = timestamp.getTime();
      timestamp = timestamp/1000;

      var msPerMinute = 60 * 1000;
      var msPerHour = msPerMinute * 60;
      var msPerDay = msPerHour * 24;
      var msPerMonth = msPerDay * 30;

      var current = Date.parse(new Date()); 
      var elapsed = current - timestamp*1000;
      if (elapsed < msPerMinute) {
        return "刚刚";   
      } 
      else if (elapsed < msPerHour) {
        return Math.round(elapsed/msPerMinute) + "分钟前";   
      }
      else if (elapsed < msPerDay ) {
        return Math.round(elapsed/msPerHour ) + "小时前";   
      }
      else if (elapsed < msPerMonth) {
        return Math.round(elapsed/msPerDay) + "天前";   
      }
      return year + "-" + month + "-" + day;
    },
  },
};
</script>

<style>
.msg-list {
  width: 100%;
  height: 80px;
  background-color: #fff;
  position: relative;
}

.title-name {
  background-color: rgb(68, 165, 133);
  height: 30px;
  width: 96%;
  margin-left: 2%;
  text-align: center;
}

.u-msg-div {
  background-color: #fff;
  height: 580px;
  overflow-y: auto;
}

.u-msg-name {
  position: absolute;
  margin-top: 2px;
  margin-left: 10px;
  font-size: 16px;
}

.close-btn{
  float: right;
  margin-top: -5px;
}

.u-msg-date {
  margin-left: 10px;
  color: #808080;
}

.send-msg-div {
  background-color: rgb(235, 235, 235);
  width: 96%;
  margin: auto;
  height: 380px;
  overflow-y: auto;
}

/* 对话部分 */
.msg-right {
  min-height: 70px;
  margin-right: 20px;
}

.face-right {
  float: right;
}

.content-right {
  float: right;
  max-width: 80%;
  margin-right: 10px;
  margin-top: 15px;
  background: rgb(68, 165, 133);
  color: #fff;
  font-size: 1rem;
  border-radius: 3px;
  padding: 5px 10px 5px 10px;
}

.msg-left {
  margin-left: 20px;
  min-height: 70px;
}

.content-l-div{
  float: left;
  margin-left:10px;
  margin-top: 10px;
  max-width: 80%;
  background: #fff;
  padding: 5px 10px 5px 10px;
  border-radius: 3px;
}

.content-left { 
  font-size: 1rem;
}

/*发送*/
.input-msg {
  margin-top: 20px;
  width: 96%;
  margin-left: 2%;
}

.btn-msg {
  background-color: rgb(68, 165, 133);
  color: #fff;
  float: right;
  margin-right: 20px;
  margin-top: 10px;
}
</style>